package com.rede.didiok.community.security.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.TypeReference;
import com.rede.didiok.common.dto.user.UserDto;
import com.rede.didiok.common.enums.StatusEnum;
import com.rede.didiok.common.exception.exceptionType.FeignException;
import com.rede.didiok.common.feign.UserFeignClient;
import com.rede.didiok.common.utils.R;
import com.rede.didiok.community.security.SecurityUserFactory;
import com.rede.didiok.community.security.exception.UserNonactivatedException;

/**
 * 将SpringSecurity中的用户管理和数据库的管理员对应起来
 *
 */
@Service
@Slf4j
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserFeignClient userFeignClient;

    /**
     * @param username 浏览器输入的用户名【需要保证用户名的唯一性】
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名获取用户信息
        R result = userFeignClient.getByUserName(username);
        UserDto user;
        if(result.getCode()==0){
            user = result.getData(new TypeReference<UserDto>(){});
        }else {
            // 获取异常信息
            throw new FeignException("feign调用异常（根据用户名获取用户信息）：失败");
        }

        if (user == null || StatusEnum.DISABLED == user.getStatus()) {
            log.error(String.format("[%s]该账号未注册,无法登录", username));
            throw new UsernameNotFoundException(String.format("[%s]该账号未注册,无法登录", username));
        } else {
            if (StatusEnum.FREEZE == user.getStatus()) {
                log.error(String.format("[%s]该账号未激活,无法登录", username));
                throw new UserNonactivatedException(String.format("[%s]该账号未激活,无法登录", username));
            }
            return SecurityUserFactory.create(user, "web");
        }
    }
}
